import { MapConfig, MouseMapPoint, LineProps } from '../types';
import { onMounted, nextTick, unref } from 'vue';
import useMarkTool from './markTools';
import { isArray } from 'lodash-es';
import messageInfo from './info';
import axios from 'axios';
import usePolylineTool from './line';

let userConfig;

function useMap(config: MapConfig) {
  userConfig = config;
  const useMessageInfo = messageInfo();

  //需要在map容器dom加载完成后调用
  const getMapIntance = () => {
    if (!unref(userConfig.el)) return;
    const dom = unref(userConfig.el);
    return new T.Map(dom);
  };
  // 手动注册地图

  let MapIntance, markTools, lineTools;
  const handleReisterMap = async (obj?: MouseMapPoint) => {
    await nextTick();

    register(obj);
  };
  // 初始化注册地图
  const register = (obj?: MouseMapPoint): void => {
    userConfig.lat = obj?.lat ?? userConfig.lat;
    userConfig.lng = obj?.lng ?? userConfig.lng;
    userConfig.level = obj?.level ?? userConfig.level;
    const Map = getMapIntance();
    if (!Map) return;

    MapIntance = Map;
    markTools = useMarkTool({
      Map: MapIntance,
      getCurrentMarkItems: userConfig.getCurrentMarkItems as (val: any) => void,
    });

    // 设置中心区域
    const cp = new T.CoordinatePickup(Map, { callback: getMousePoint });
    cp.addEvent();
    // console.log('%c地图中心点', 'color:#8ae;font-size:20px;font-weight:bold', userConfig);

    setPosition(userConfig.lng, userConfig.lat, userConfig?.level || 18);
    lineTools = usePolylineTool({
      Map,
      lineStyle: { color: '#368fff', opacity: 1, weight: 2 },
    });
    setLineToMap(userConfig?.points || [], { lng: userConfig.lng, lat: userConfig.lat });
    userConfig.addClick && addMapClick(userConfig.addClick);
  };

  // 设置地图中心经纬度地址
  function setPosition(longitude: string | number, latitude: string | number, level = 18) {
    const lnglat = new T.LngLat(longitude, latitude);
    MapIntance.centerAndZoom(lnglat, level);
  }
  // 获取当前鼠标点击处的经纬度
  function getMousePoint(lnglat: MouseMapPoint) {
    userConfig.getClickPoint && userConfig.getClickPoint(lnglat);
  }

  // 添加地图点击
  function addMapClick(callback: Fn) {
    removeMapClick(callback);
    MapIntance.addEventListener('click', callback);
  }

  //移除地图点击事件
  function removeMapClick(callback) {
    MapIntance.removeEventListener('click', callback);
  }

  // 获取markTools事件 需要在map容器dom加载完成后调用
  function getMarkToolsMethods() {
    return markTools;
  }
  // 获取地图上的所有覆盖物
  function getOverlays() {
    return MapIntance.getOverlays();
  }
  // 清除地图上的所有覆盖物
  function clearOverLays() {
    return MapIntance.clearOverLays();
  }
  // 手动添加轨迹线
  function setLineToMap(points: LineProps[], lnglat: MouseMapPoint) {
    // 每次绘制前将之前绘制的点线去除
    const [_, { addLineToMap }] = lineTools;
    clearOverLays();
    // 重新绘制中心点

    if (isArray(points) && points.length) {
      setPosition(points[0].lng, points[0].lat, userConfig?.level || 18);
      points.forEach((i) => {
        // 添加初始化中心点标注
        const marks = markTools.addMarkToolIconExample(i.lng, i.lat);
        markTools.addClickToMarkItem(marks, async () => {
          await getAddressName(i.lng, i.lat, (address) => {
            useMessageInfo.setContent(`
            <div style="color:#1153D8;display:flex;align-items:center">
            <img src="http://api.tianditu.gov.cn/v4.0/image/marker-icon.png" style="width:10px;height:14px;margin-right:4px"/>
            当前所在(半径100米内活动)</div>
            <div style="#333333;font-size:14px;font-weight:600">${address}
              <span style="color:orange;display:${i?.emulatorNum >= 3 ? 'block' : 'none'}">(模拟器${
              i?.emulatorNum ?? ''
            })</span>
            </div>
            <div>${i?.uploadTime ?? ''}</div>
          `);
            marks.openInfoWindow(useMessageInfo);
          });
        });
      });

      MapIntance.addOverLay(addLineToMap(points));
    } else {
      setPosition(lnglat.lng, lnglat.lat, userConfig?.level || 18);
      const marks = markTools.addMarkToolIconExample(lnglat.lng, lnglat.lat);

      markTools.addClickToMarkItem(marks, async () => {
        await getAddressName(lnglat.lng, lnglat.lat, (address) => {
          useMessageInfo.setContent(`
          <div style="color:#1153D8;display:flex;align-items:center">
          <img src="http://api.tianditu.gov.cn/v4.0/image/marker-icon.png" style="width:10px;height:14px;margin-right:4px"/>
          当前所在(半径100米内活动)</div>
          <div style="#333333;font-size:14px;font-weight:600">${address}
          <span style="color:orange;display:${
            lnglat?.emulatorNum >= 3 ? 'block' : 'none'
          }">(模拟器${lnglat?.emulatorNum})</span></div>
         
        `);
          marks.openInfoWindow(useMessageInfo);
        });
      });
    }
  }
  // 根据经纬度获取具体地址
  const getAddressName = (lon, lat, callback) => {
    const postStr = { lon: lon, lat: lat, ver: '4.0' };
    axios
      .get(`https://api.tianditu.gov.cn/geocoder?postStr=${JSON.stringify(postStr)}`, {
        params: {
          // postStr: { lon: lon, lat: lat, ver: '4.0' },

          type: 'geocode',
          tk: '1cfe42b38dc16d91a92adba719b7517c',
        },
      })
      .then(({ data: { result } }) => {
        callback && callback(`${result.formatted_address}`);
      });
  };

  onMounted(() => {
    nextTick(() => {
      register();
    });
  });

  return {
    getMapIntance,
    setPosition,
    handleReisterMap,
    removeMapClick,
    getMarkToolsMethods,
    setLineToMap,
    getOverlays,
    clearOverLays,
  };
}

export default useMap;
